package com.ibeeking.found.uaa.cp.config.auth.grant;

import com.ibeeking.found.uaa.cp.config.auth.token.AbstractCustomTokenGranter;
import com.ibeeking.found.uaa.cp.model.CpUserDetails;
import com.ibeeking.found.uaa.cp.model.SmsCodeModel;
import com.ibeeking.found.uaa.cp.service.ICpUserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * @Author ibeeking
 */
public class SmsCodeTokenGranter extends AbstractCustomTokenGranter {

    private static final String GRANT_TYPE = "sms_code";
    private static final String MOBILE_PARAM = "mobile";
    private static final String CODE_PARAM = "code";
    private static final String KEY_PARAM = "key";

    private final ICpUserDetailsService userDetailsServiceImpl;

    public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsServiceImpl, OAuth2RequestFactory requestFactory, ICpUserDetailsService userDetailsServiceImpl) {
        super(tokenServices, clientDetailsServiceImpl, requestFactory, GRANT_TYPE);
        this.userDetailsServiceImpl = userDetailsServiceImpl;
    }

    @Override
    protected CpUserDetails getUserDetails(Map<String, String> parameters) {
        String mobile = parameters.get(MOBILE_PARAM);
        String smsCode = parameters.get(CODE_PARAM);
        String key = parameters.get(KEY_PARAM);
        SmsCodeModel smsCodeModel = new SmsCodeModel();
        smsCodeModel.setCode(smsCode);
        smsCodeModel.setMobile(mobile);
        smsCodeModel.setKey(key);
        return userDetailsServiceImpl.loadUserByPhoneAndSmsCode(smsCodeModel);
    }
}
